﻿using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;

namespace Sigma.Admin.API.Authoriza.Handler
{
    public class PermissionKeyHandler: AuthorizationHandler<PermissionRequirement>
    {
        

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            var keys = context.User.FindFirst("pkey")?.Value;
            if (string.IsNullOrWhiteSpace(keys))
            {
                return Task.CompletedTask;
            }
                
            var keylist = JsonConvert.DeserializeObject<List<string>>(keys);
            if (keylist.Contains(requirement.Permission))
                context.Succeed(requirement);
            return Task.CompletedTask;
        }
    }
}
